<template>
	<section>
		<!--&lt;!&ndash;高级查询&ndash;&gt;-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--&lt;!&ndash;列表&ndash;&gt;-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="220" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="编号" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" sortable>
				<template scope="scope">
					<span v-if="scope.row.state === 0" style="color: green">启用</span>
					<span v-else-if="scope.row.state === -1" style="color: red">禁用</span>
					<span v-else style="color: dimgrey">未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="180" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="180" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--&lt;!&ndash;分页条&ndash;&gt;-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   :current-page="currentPage"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--&lt;!&ndash;新增/编辑界面&ndash;&gt;
		&lt;!&ndash; :visible.sync  控制dialog是否显示
         :rules  绑定表单校验规则
         ref="saveForm"  给当前表单取一个别名

         prop:绑定校验规则的名称-->

       <!--&ndash;&gt;-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="0">启用</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="管理员">
					<el-select v-model="saveForm.manager" clearable value-key="id" placeholder="请选择">
						<!--&lt;!&ndash;下拉选项
						  :key=""  //唯一标识
						  :label 选择之后展示到选择框中的值
						  :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
						     必须要写  value-key="id"
						&ndash;&gt;-->
						<el-option
								v-for="item in employees"
								:key="item.id"
								:label="item.username"
								:value="item">
							<span style="float: left">{{ item.username }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上级部门">
					<el-cascader v-model="saveForm.parent"
								 :options="deptTree"
								 :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
								 clearable></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    export default {
        data() {
            return {
                title:"",
                filters: {
                    keyword: ''
                },
                departments: [],
                employees:[],//部门管理源下拉列表基础数据
                deptTree:[],
                total: 0,
                currentPage: 1,
                pageSize:10,

                listLoading: false,
                sels: [],//列表选中行

                saveFormVisible: false,//新增界面是否显示
                saveLoading: false,
                saveFormRules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    sn: [
                        { required: true, message: '请输入编号', trigger: 'blur' }
                    ]
                },
                //新增界面数据
                saveForm: {
                    id:null,
                    name: "",
                    sn: "",
                    state: 0,
                    manager: null,
                    parent: null
                }
            }
        },
        methods: {
            search(){//做高级查询,一定要定位到第一页
                this.currentPage = 1;
                this.getDepartments();
            },
            handleCurrentChange(val) {
                this.currentPage = val;//点击页码之后给模型层赋值
                this.getDepartments();
            },
            //获取部门列表
            getDepartments() {
                let para = {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword
                };

                this.listLoading = true;//开启忙等框
                //NProgress.start();
                //发送axios请求从后端  8080 拿数据
                this.$http.post("/dept/page",para)
                    .then(result=>{
                        this.listLoading = false;//开启忙等框
                        console.log(result);//
                        result = result.data;//PageList
                        this.departments = result.rows;
                        this.total = result.total;
                    })
                    .catch(result=>{
                        console.log(result);
                        this.$message({
                            type: 'error',
                            message: '系统错误,我们正在和程序员小哥哥勾兑!!'
                        });
                    });
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {//点击确定
                    this.listLoading = true;

                    this.$http.delete("/dept/"+row.id)
                        .then(result=>{
                            this.listLoading = false;
                            result = result.data;//AjaxResult success:true/false
                            if(result.success){//删除成功
                                this.$message({
                                    type: 'success',
                                    message: result.message
                                });
                                //重新加载页面数据  要  要不要定位到第一页
                                this.currentPage = 1;
                                this.getDepartments();
                            }else{
                                this.$message({
                                    type: 'error',
                                    message: result.message
                                });
                                //重新加载页面数据  要  要不要定位到第一页
                                this.currentPage = 1;
                                this.getDepartments();
                            }
                        })
                        .catch(result=>{
                            this.listLoading = false;
                            console.log(result);
                            this.$message({
                                type: 'error',
                                message: '系统错误,我们正在和程序员小哥哥勾兑!!'
                            });
                        })
                }).catch(() => {//点击取消按钮

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.getDeptTree();//点击按钮的时候触发加载部门树
                this.title = "编辑";
                this.saveFormVisible = true;
                this.saveForm = Object.assign({}, row);//克隆一份数据用来做回显
                if(row.dirPath){//不为空才执行  上级部门回显
                    //  /52/53/54
                    let array = row.dirPath.split("/");// ["","52","53","54"]
                    let tmp = [];
                    for(let i=1;i<array.length-1;i++){
                        tmp.push(parseInt(array[i]));
                    }//[52,53]
                    console.log(tmp);
                    this.saveForm.parent = tmp;
                }
            },
            //显示新增界面
            handleAdd: function () {
                this.getDeptTree();//点击按钮的时候触发加载部门树
                this.title = "新增";
                this.saveFormVisible = true;
                this.saveForm = {//表格初始化
                    id:null,
                    name: "",
                    sn: "",
                    state: 0,
                    manager: null,
                    parent: null
                };
            },
            //编辑
            saveSubmit: function () {
                // this.$refs.saveForm 找到saveFrom
                this.$refs.saveForm.validate((valid) => {
                    if (valid) {// 表单校验成功
                        this.$confirm('确认提交吗？', '提示', {})
                            .then(() => {//点击确定要提交
                                this.saveLoading = true;//开启按钮忙等
                                //NProgress.start();
                                let para = Object.assign({}, this.saveForm);
                                //处理后端需要的数据格式
                                if(para.parent){// [2,7]
                                    para.parent = {"id":para.parent[para.parent.length-1]}
                                }

                                this.$http.post("/dept/save",para)
                                    .then(result=>{
                                        this.saveLoading = false;//关闭按钮忙等
                                        result = result.data;
                                        if(result.success){//删除成功
                                            this.$message({
                                                type: 'success',
                                                message: result.message
                                            });
                                            //重新加载页面数据
                                            this.currentPage = 1;
                                            this.getDepartments();
                                            this.$refs['saveForm'].resetFields();//重置表单校验
                                            this.saveFormVisible = false;//关闭模态框
                                        }else{
                                            this.$message({
                                                type: 'error',
                                                message: result.message
                                            });
                                            //重新加载页面数据
                                            this.currentPage = 1;
                                            this.getDepartments();
                                        }
                                    })
                                    .catch(result=>{
                                        this.saveLoading = false;//关闭按钮忙等
                                        console.log(result);
                                        this.$message({
                                            type: 'error',
                                            message: '系统错误,我们正在和程序员小哥哥勾兑!!'
                                        });
                                    })
                            });
                    }
                });
            },
            selsChange: function (sels) {//复选框勾选的时候触发 当前复选框选中的所有行的数据
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                //批量删除注释掉  toString();
                var ids = this.sels.map(item => item.id);// .toString();// [1,2,5]  1,2,5
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    console.log(ids);
                    this.$http.patch("/dept",ids)
                        .then(result=>{
                            this.listLoading = false;
                            result = result.data;//AjaxResult success:true/false
                            if(result.success){//删除成功
                                this.$message({
                                    type: 'success',
                                    message: result.message
                                });
                                //重新加载页面数据  要  要不要定位到第一页
                                this.currentPage = 1;
                                this.getDepartments();
                            }else{
                                this.$message({
                                    type: 'error',
                                    message: result.message
                                });
                                //重新加载页面数据  要  要不要定位到第一页
                                this.currentPage = 1;
                                this.getDepartments();
                            }
                        })
                        .catch(result=>{
                            this.listLoading = false;
                            console.log(result);
                            this.$message({
                                type: 'error',
                                message: '系统错误,我们正在和程序员小哥哥勾兑!!'
                            });
                        })


                }).catch(() => {

                });
            },
            getEmployees(){
                this.$http.get("/employee/list")
                    .then(result=>{
                        this.employees = result.data;
                    })
            },
            getDeptTree(){
                this.$http.post("/dept/tree")
                    .then(result=>{
                        this.deptTree = result.data;
                    })
            }
        },
        mounted() {
            this.getDepartments();
            this.getEmployees();
        }
    }

</script>

<style scoped>

</style>
